/*
 * @Description: 缓存淘汰算法（LRU）
 * @Author: Empty
 * @Date: 2019-07-24 16:16:36
 */
package replacement

import (
	"fmt"
	"go_algorithm/singlelinkedlist"
)

// 缓存结构体
type Cache struct {
	linkedlist *singlelinkedlist.SingleLinkedList
	length     int
}

// 初始化缓存
func NewCache(v interface{}) *Cache {
	return &Cache{singlelinkedlist.NewSingleLinkedList(), v.(int)}
}

// 存入缓存
func (this *Cache) InsertCache(v interface{}) bool {

	// 查询是否存在
	var listnode *singlelinkedlist.SingleListNode = nil
	for cur := this.linkedlist.GetHead().GetNext(); cur != nil; cur = cur.GetNext() {
		if cur.GetValue() == v {
			listnode = cur
			break
		}
	}

	// 如果存在
	if listnode != nil {
		this.linkedlist.DeleteSingleListNode(listnode)
		this.linkedlist.InsertToHead(v)
	} else {
		// 链表满了
		if this.linkedlist.GetLength() == this.length {
			tail := this.linkedlist.GetTail()
			this.linkedlist.DeleteSingleListNode(tail)
		}
		this.linkedlist.InsertToHead(v)
	}

	return true
}

// 打印缓存队列
func (this *Cache) PrintCache() {
	for cur := this.linkedlist.GetHead().GetNext(); cur != nil; cur = cur.GetNext() {
		fmt.Printf("%+v", cur.GetValue())
		if cur.GetNext() != nil {
			fmt.Print("->")
		}
	}
	fmt.Println()
}
